﻿#if UNITY_EDITOR

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;


namespace HEFramework
{
    /// <summary>
    ///
    /// 框架脚本扩展类
    /// 
    /// ----------------------------------------
    /// 作者 hep
    /// 创建时间：2024-01-04 13:45:57
    /// ----------------------------------------
    /// </summary>
    public class FrameworkScriptAutoBuildEditor : EditorWindow, IHasCustomMenu
    {
        public enum eType
        {
            View,
            UnView,
        }

        private static FrameworkScriptAutoBuildEditor window;

        /// <summary>
        /// 编辑器扩展脚本类文件路径
        /// </summary>
        private static readonly string scriptFilePath = "Assets/Scripts/HEFramework/Editor/FrameworkScriptAutoBuildEditor.cs";

        /// <summary>
        /// 模板路径
        /// </summary>
        private static readonly string templatePath = "Assets/Scripts/HEFramework/Editor/Template";

        /// <summary>
        /// 目标路径
        /// </summary>
        private static readonly string targetPath = $"Assets/Scripts";

        /// <summary>
        /// 脚本后缀
        /// </summary>
        private static string scriptExtension = ".cs";

        /// <summary>
        /// 文本后缀
        /// </summary>
        private static string txtExtension = ".txt";

        /// <summary>
        /// 输入的脚本名称
        /// </summary>
        private string scriptName;

        /// <summary>
        /// 是否热更
        /// </summary>
        private eType type;

        /// <summary>
        /// 是否初始化
        /// </summary>
        private bool isAwake;

        /// <summary>
        /// 是否帧更新
        /// </summary>
        private bool isUpdate;

        /// <summary>
        /// 是否初始化
        /// </summary>
        private bool isDestroy;

        /// <summary>
        /// Unity菜单选项附加
        /// </summary>
        [MenuItem("MyTools/ScriptBuild", false, 1)]
        public static void OpenSettingsWindow()
        {
            try
            {
                if (EditorApplication.isCompiling)
                {
                    return;
                }

                var window = GetWindowWithRect<FrameworkScriptAutoBuildEditor>(new Rect(0, 0, 400, 200), true, "Script Build", true);
                window.Show();
            }
            catch (Exception e)
            {
                Debug.Log(e.Message);
            }
        }


        /// <summary>
        /// 打开脚本的方法
        /// </summary>
        /// <param name="menu"></param>
        public void AddItemsToMenu(GenericMenu menu)
        {
            //附加内容添加
            menu.AddItem(new GUIContent("Open Script"), false, () =>
            {
                TextAsset obj = AssetDatabase.LoadAssetAtPath<TextAsset>(scriptFilePath);
                if (obj != null)
                {
                    Selection.activeObject = obj;
                    AssetDatabase.OpenAsset(obj, 0);
                }
            });
        }


        void OnGUI()
        {
            GUILayout.BeginVertical("box");
            GUILayout.Label("实体创建");
            GUILayout.EndVertical();


            GUILayout.BeginHorizontal("box");
            GUILayout.BeginVertical();
            DrawLine();
            scriptName = EditorGUILayout.TextField(scriptName);

            type = (eType)EditorGUILayout.EnumPopup("类型", type);

            GUILayout.Label("可选项");
            isAwake = true;
            isUpdate = GUILayout.Toggle(isUpdate, "帧更新");
            isDestroy = GUILayout.Toggle(isDestroy, "销毁");
            DrawLine();
            GUILayout.BeginHorizontal("box");
            GUILayout.BeginVertical();
            GUILayout.EndVertical();
            GUILayout.EndHorizontal();
            if (GUILayout.Button("创建"))
            {
                CreateFile();
            }

            GUILayout.EndVertical();
            GUILayout.EndHorizontal();
        }


        /// <summary>
        /// 给界面划横线
        /// </summary>
        private void DrawLine()
        {
            GUILayout.Box("", GUILayout.Height(2F), GUILayout.ExpandWidth(true));
        }


        /// <summary>
        /// 创建文件
        /// </summary>
        private void CreateFile()
        {
            string entity_file_path = templatePath + "/" + "Entity" + txtExtension;
            string system_file_path = templatePath + "/" + "System" + txtExtension;
            string awake_system_file_path = templatePath + "/" + "AwakeSystem" + txtExtension;
            string update_system_file_path = templatePath + "/" + "UpdateSystem" + txtExtension;
            string destroy_system_file_path = templatePath + "/" + "DestroySystem" + txtExtension;
            //两者都存在
            if (System.IO.File.Exists(entity_file_path) && System.IO.File.Exists(system_file_path))
            {
                string t = string.Empty;
                string e_folder = string.Empty;
                string s_folder = string.Empty;
                string text = string.Empty;
                UTF8Encoding encoding = new UTF8Encoding(true, false);
                StreamReader streamReader;
                StreamWriter streamWriter;
                switch (type)
                {
                    case eType.View:
                        e_folder = "ModelView";
                        s_folder = "HotfixView";
                        break;
                    case eType.UnView:
                        e_folder = "Model";
                        s_folder = "Hotfix";
                        break;
                }

                t = targetPath + "/" + e_folder + "/" + scriptName + scriptExtension;
                //已经存在脚本文件
                if (System.IO.File.Exists(t))
                {
                    Debug.LogError(t + "exist");
                    return;
                }

                string dir = System.IO.Path.GetDirectoryName(t);
                //脚本创建
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                streamReader = new StreamReader(entity_file_path);
                text = streamReader.ReadToEnd();
                streamReader.Close();

                //补上接口
                string istring = string.Empty;
                if (isAwake)
                {
                    istring += ", IAwake";
                }

                if (isUpdate)
                {
                    istring += ", IUpdate";
                }

                if (isDestroy)
                {
                    istring += ", IDestroy";
                }

                text = Regex.Replace(text, "@", scriptName);
                text = text.Replace("&", istring);

                streamWriter = new StreamWriter(t, false, encoding);
                streamWriter.Write(text);
                streamWriter.Close();


                UnityEngine.Debug.Log("EntityCreate -> " + t);

                //---------------------------------------------------------------------------

                t = targetPath + "/" + s_folder + "/" + scriptName + "System" + scriptExtension;
                //已经存在脚本文件
                if (System.IO.File.Exists(t))
                {
                    Debug.LogError(t + "exist");
                    return;
                }

                dir = System.IO.Path.GetDirectoryName(t);
                //脚本创建
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                streamReader = new StreamReader(system_file_path);
                text = streamReader.ReadToEnd();
                streamReader.Close();


                istring = string.Empty;
                if (isAwake)
                {
                    streamReader = new StreamReader(awake_system_file_path);
                    istring = streamReader.ReadToEnd();
                }

                text = text.Replace("&_1", istring);

                istring = string.Empty;
                if (isUpdate)
                {
                    streamReader = new StreamReader(update_system_file_path);
                    istring = streamReader.ReadToEnd();
                }

                text = text.Replace("&_2", istring);

                istring = string.Empty;
                if (isDestroy)
                {
                    streamReader = new StreamReader(destroy_system_file_path);
                    istring = streamReader.ReadToEnd();
                }

                text = text.Replace("&_3", istring);

                text = text.Replace("@", scriptName);

                streamWriter = new StreamWriter(t, false, encoding);
                streamWriter.Write(text);
                streamWriter.Close();

                UnityEngine.Debug.Log("SystemCreate -> " + t);


                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
            }
            else
            {
                UnityEngine.Debug.Log("Check filePath ->" + entity_file_path + " | " + system_file_path);
            }
        }
    }
}
#endif